package br.edu.ufc.deti.cripto;

import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 * 	Classe respons�vel fazer encripta��o/descripta��o do 
 * c�digo da proposta, usado no processo da reimpress�o.
 * 
 * @author
 */
public class Crypto {
	/**
	 * Defini a chave de criptografia usada para criptografar o n�mero da proposta para reimpress�o.
	 */
	//private static final byte[] raw = new String("r��!?��+��?9_�").getBytes();
	//private static final byte[] raw = new String("rÀi!?ë¹ë+«š?%9_Ä").getBytes();
	private static byte[] raw = Crypto.generatePassword();

	/**
	 * @param codigo - c�digo da proposta.
	 * @return String - c�digo criptografado do n�mero da proposta.
	 * @throws NoSuchAlgorithmException
	 * @throws NoSuchPaddingException
	 * @throws InvalidKeyException
	 * @throws IllegalStateException
	 * @throws IllegalBlockSizeException
	 * @throws BadPaddingException
	 */
	public static String encrypt( String codigo ) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalStateException, IllegalBlockSizeException, BadPaddingException{
		SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
		Cipher cipher = Cipher.getInstance("AES");
		cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
		byte[] encrypted = cipher.doFinal(codigo.getBytes());
		String hexadecimal = printHexBinary( encrypted );
		return hexadecimal;
	}

	/**
	 * @param hexadecimal - c�digo em representa��o hexadecimal do c�digo da proposta.
	 * @return String - c�digo decriptado do c�digo da proposta.
	 * @throws NoSuchAlgorithmException
	 * @throws NoSuchPaddingException
	 * @throws InvalidKeyException
	 * @throws IllegalStateException
	 * @throws IllegalBlockSizeException
	 * @throws BadPaddingException
	 */
	public static String decrypt( String hexadecimal ) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalStateException, IllegalBlockSizeException, BadPaddingException{
		byte[] encrypted = parseHexBinary( hexadecimal );
		SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
		Cipher cipher = Cipher.getInstance("AES");
		cipher.init(Cipher.DECRYPT_MODE, skeySpec);
		byte[] original = cipher.doFinal(encrypted);
		String originalString = new String(original);
		return originalString;
	}

	/**
	 * 	Faz trasforam��o de String da base Hexa para a Base Bin�ria.
	 * @param s - String na base hexa.
	 * @return s[] - String na base bin�ria.
	 */
	public static byte[] parseHexBinary(String s) {
		final int len = s.length();

		// "111" is not a valid hex encoding.
		if( len%2 != 0 )
			throw new IllegalArgumentException("hexBinary needs to be even-length: "+s);

		byte[] out = new byte[len/2];

		for( int i=0; i<len; i+=2 ) {
			int h = hexToBin(s.charAt(i  ));
			int l = hexToBin(s.charAt(i+1));
			if( h==-1 || l==-1 )
				throw new IllegalArgumentException("contains illegal character for hexBinary: "+s);

			out[i/2] = (byte)(h*16+l);
		}
		return out;
	}

	/**
	 * 	Faz trasforam��o de String da base Hexa para a Base Bin�ria.
	 * @param s - caracter na base hexa.
	 * @return s[] - int na base bin�ria.
	 */
	private static int hexToBin( char ch ) {
		if( '0'<=ch && ch<='9' )    return ch-'0';
		if( 'A'<=ch && ch<='F' )    return ch-'A'+10;
		if( 'a'<=ch && ch<='f' )    return ch-'a'+10;
		return -1;
	}
	/**
	 * Vari�vel com caracteres da base hexadecimal.
	 */
	private static final char[] hexCode = "0123456789ABCDEF".toCharArray();

	/**
	 * 	Retorna String que representa o array de bytes.
	 * @param data - array de bytes.
	 * @return String - em c�digo hexa. 
	 */
	public static String printHexBinary(byte[] data) {
		StringBuffer r = new StringBuffer(data.length*2);
		for (int i = 0; i < data.length; i++) {
			byte b = data[i];
			r.append(hexCode[(b >> 4) & 0xF]);
			r.append(hexCode[(b & 0xF)]);
		}
		return r.toString();
	}

	/**
	 * 	Trasforma array de bytes em String na base hexa.
	 * @param buf - array de bytes.
	 * @return String na base hexa.
	 */
	private static String asHex(byte buf[]) {
		StringBuffer strbuf = new StringBuffer(buf.length * 2);
		int i;
		for (i = 0; i < buf.length; i++) {
			if (((int) buf[i] & 0xff) < 0x10) {
				strbuf.append("0");
			}
			strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
		}
		return strbuf.toString();
	}
	
	/**
	 * 	Transforma String na base hexa para a base bin�ria.
	 * @param hex - String na base hexa.
	 * @return Array de byte na base bin�ria.
	 */
	private static byte[] asByteArray (String hex){
		BigInteger bi = new BigInteger(hex, 16);
		byte[] bytes = bi.toByteArray();
		byte[] bytesFinal = removeRepresentativeDigit(bytes);
		return bytesFinal;
	}

	private static byte[] removeRepresentativeDigit( byte[] bytes ) {
		byte[] bytesFinal = new byte[16];
		for (int i =0; i < bytes.length - 1; i++){
			bytesFinal[i] = bytes[i+1];
		}
		return bytesFinal;
	}
	
	public static void main( String[] args ) throws Exception {
		String content = "rafael";
		System.out.println("Original string: " + content );
		String hexadecimal = encrypt( content );
		System.out.println("Encrypted string(Hexadecimal): " + hexadecimal);
		String decrypted = decrypt( hexadecimal );
		System.out.println("Decrypted string: " + decrypted);
	}

	public static byte[] generatePassword (){
		KeyGenerator kgen = null;
		try {
			kgen = KeyGenerator.getInstance("AES");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		kgen.init(128);
		SecretKey skey = kgen.generateKey();
		System.out.println(skey.getEncoded());
		return skey.getEncoded();
	}	
}
